<template>
  <el-tabs v-loading="loading" v-model="activeName">
    <el-tab-pane label="表单信息" name="form">
      <uni-async-form v-if="processFormFlag" ref="processForm" :keep-alive="processFormFlag" :path="processFormUrl">
      </uni-async-form>
      <uni-async-form v-if="taskFormFlag" ref="taskForm" :keep-alive="taskFormFlag" :path="taskFormUrl">
      </uni-async-form>
      <el-card>
        <el-form v-loading="!operate" :model="dataForm" ref="dataForm"
          :label-width="$i18n.locale === 'en-US' ? '120px' : '140px'">
          <el-form-item>
            <el-button @click="closeTab()">{{ $t('cancel') }}</el-button>
            <el-button v-if="operate" type="primary" @click="dealHandle()">{{ $t('approveManage.deal') }}
            </el-button>
            <el-button v-if="operate" @click="backHandle">驳回
            </el-button>
            <el-button v-if="operate&&transfer" @click="transferHandle">转办</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-tab-pane>
    <el-tab-pane label="审批详情" name="history">
      <process-history v-if="this.task" ref="proHistory"></process-history>
    </el-tab-pane>
    <TodoManageWander ref="todoManageWander" v-if="todoManageWanderVisible"></TodoManageWander>
  </el-tabs>
</template>
<script>
import ProcessHistory from './process-history'
import TodoManageWander from './todo-manage-wander'
import debounce from 'lodash/debounce'
import mainContent from '@/views/main-content'
import { isEmpty } from '../../../utils/validate'

var content = mainContent
export default {
  components: {
    ProcessHistory,
    TodoManageWander
  },
  data () {
    return {
      taskId: '',
      task: null,
      loading: false,
      activeName: 'form',
      processFormUrl: '',
      taskFormUrl: '',
      processFormFlag: true,
      taskFormFlag: false,
      dealFormFlag: true,
      operate: false,
      approve: 2,
      isMultiInstancehas: false,
      signature: false,
      transfer: false,
      todoManageWanderVisible: false,
      modalTaskTitle: '',
      // approveItems: [{ key: 2, value: '同意' }, { key: 3, value: '驳回' }], // 反对 6
      dataForm: {
        id: '',
        userId: '',
        procInstId: '',
        comment: '',
        type: 0,
        taskFormJson: '',
        assignees: [],
        backTaskKey: '-1',
        sendMessage: true,
        sendSms: true,
        sendEmail: true,
        approve: 2
      },
      formUrl: ''
    }
  },
  created () {
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    init () {
      this.taskId = this.$route.params.taskId
      // this.processFormUrl = 'flowable/bpmFormFee'
      this.getTaskInfo()
    },
    getTaskInfo () {
      this.$http.get(`/flowable/task/info/${this.taskId}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return
        }
        if (res.data) {
          this.task = res.data.task
          this.$route.params.bizId = this.task.bizId
          this.$route.params.formId = this.task.formId
          this.$route.params.procInstId = this.task.procInstId
          this.$route.params.procBizId = this.task.procBizId
          // console.log('1', this.$route.params)
          this.getUrl(res.data.bpmUrls)
          this.getTaskDef(res.data.bpmTaskExt.formDTO)
          this.isMultiInstancehas = res.data.bpmTaskExt.isMultiInstancehas
          this.transfer = res.data.bpmTaskExt.transfer

          this.signature = res.data.bpmTaskExt.signature
        } else {
          return this.$message.error('未获取到任务！')
        }
      }).catch(() => { })
    },
    getTaskDef (formData) {
      if (formData) {
        this.processFormFlag = formData.processFormFlag
        this.taskFormFlag = formData.taskFormFlag
        this.dealFormFlag = formData.dealFormFlag
        if (formData.processFormUrl && formData.processFormUrl !== 'default') {
          this.processFormUrl = formData.processFormUrl
        } else {
          this.processFormUrl = this.formUrl
        }
        this.taskFormUrl = formData.taskFormUrl
      } else {
        this.processFormUrl = this.formUrl
      }
      this.wanderInit()
    },
    // 获取表单配置url
    getUrl (data) {
      if (isEmpty(data.pc.url)) {
        return this.$message.error('流程对应的表单没有定义')
      }
      this.formUrl = data.pc.url
    },
    setPageState () {
      this.operate = true
    },
    wanderInit () {
      this.setPageState()
    },
    dealHandle () {
      this.approve = 2
      this.dataFormSubmitHandle()
    },
    // 驳回
    backHandle () {
      this.approve = 3
      this.dataFormSubmitHandle()
    },
    // 转办
    transferHandle () {
      this.approve = 4
      this.dataFormSubmitHandle()
    },

    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      // 判断是否需求节点表单
      if (this.taskFormFlag && this.approve === 2) {
        // 先调用节点表单编辑校验
        let taskForm = this.$refs.taskForm.$children[0]
        let flag = taskForm.validate()
        if (!flag) {
          return !flag
        }
        taskForm.dataForm.bizId = this.task.bizId
        // 节点表单 json 序列化
        let formJsonStr = JSON.stringify(taskForm.dataForm)
        // 将节点表单 json化 传输给 dataForm
        this.dataForm.taskFormJson = formJsonStr
      }
      // 调用表单审批
      // this.dealTask(this.dataForm)
      this.todoManageWanderVisible = true
      this.$nextTick(() => {
        let wander = this.$refs.todoManageWander
        this.dataForm = {
          ...this.dataForm,
          ...this.task
        }
        if (!wander.action) {
          wander.action = {}
        }
        wander.isMultiInstancehas = this.isMultiInstancehas
        wander.transfer = this.transfer
        if (wander.transfer) {
          // 只允许实际审批人转办
          wander.transfer = this.task.assignee === this.task.owner
        }
        // wander.
        wander.signature = this.signature

        wander.action.data = this.dataForm
        wander.action.dealFormFlag = this.dealFormFlag
        wander.isBack = this.approve === 3
        wander.isTransfer = this.approve === 4
        // wander.approve = this.approve

        wander.action.closeTab = () => {
          this.closeTab()
        }
        // 保存自定义表单到流程变量
        if (this.dataForm.taskFormJson && this.approve === 2) {
          this.$http.post('/flowable/task/setVariableSyncFormData', this.dataForm).then(({ data: res }) => {
            if (res.code !== 0) {
              return
            }
            // 加载审核窗口
            wander.wanderInit()
          }).catch(() => { })
        } else {
          // 加载审核窗口
          wander.wanderInit()
        }
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    // 关闭 tab
    closeTab () {
      content.methods.tabRemoveHandle(this.$route.name)
      this.$emit('refreshDataList')
    }
    // handleClick (tab, event) {
    //   if (this.activeName === 'history') {
    //     this.$refs.proHistory.init()
    //   }
    // }

  }
}
</script>
